<?php
function ftp_mkdir_recusive($con_id,$path){
        $fullpath = ftp_pwd($con_id);
        foreach(explode("/",$path) as $part){
                $fullpath .= $part."/";
                if(empty($part)){
                        continue;
                }
                if(!@ftp_chdir($con_id, $fullpath)){
                        if(@ftp_mkdir($con_id, $part)){
                                ftp_chdir($con_id, $part);
                        }else{
                                return false;
                        }
                }
        }
        return true;
}


class mdl_news extends ujn_model {
	
	private function bind_thumb() {
		if($_FILES['thumb']['error'] == 0) {
			$f = $_FILES['thumb'];
			
			$fdir = date('/Y/md/');
			$fname = time() . '.jpg';
			
			if(!is_dir(ujn::get_cfg('thumb_path') . $fdir)) {
				mkdir(ujn::get_cfg('thumb_path') . $fdir, 0777, true);
			}
			$real_file = ujn::get_cfg('thumb_path') . $fdir . $fname;
			
			$image = $f["tmp_name"];
			$fnt = ujn::get_cfg('lib_path') . 'font.ttf';
			$str = "可可英语 www.kekenet.com";
			
			$size = 12;
			$angle = 0;
			$ar = imagettfbbox($size, 0, $fnt, $str);
			$width = $ar[2];
			$height = max($size,$ar[1]-$ar[5]);
			
			$s = getimagesize($image);
			$s_width = $s[0];
			$s_height = $s[1];
			
			$im = imagecreatefromjpeg($image); // b 184 g: 207 r: 202
			$color = imagecolorallocatealpha($im, 202, 207, 184, 1);
			imagettftext($im, $size, $angle, $s_width - $width - 15, $s_height - $height + 10, $color, $fnt, $str);
			
			imagejpeg($im, $real_file);
			imagedestroy($im);
			
			// move_uploaded_file($f["tmp_name"], $real_file);
			
			$ret = ujn::get_cfg('thumb_url') . $fdir . $fname;
			return $ret;
		}
		
		return '';
	}
	
	private function bind_music($p) {
		if(isset($p['file_url']) && !empty($p['file_url'])) { 
			return $p['file_url'];
		}
		/*
		$o = '';
		if($_FILES['music_file']['error'] == 0) {
			$f = $_FILES['music_file'];
		
			$fdir = date('/Y/m/');
			$fname = $f['name'];
		
			if(!is_dir(ujn::get_cfg('music_path') . $fdir)) {
				mkdir(ujn::get_cfg('music_path') . $fdir, 0777, true);
			}
			$real_file = ujn::get_cfg('music_path') . $fdir . $fname;
			if(move_uploaded_file($f["tmp_name"], $real_file)) {
				$o = "Sound/tmp/{$fdir}{$fname}";
				
				// 音频
				$conn = ftp_connect("61.172.249.117") or die("Could not connect");
				ftp_login($conn,'kekemp3admin','c%289b48fd9d7bac4&');
				ftp_mkdir_recusive($conn, dirname($o));
				ftp_put($conn,$fname,$real_file,FTP_ASCII);
				ftp_close($conn);
				
				// 下载
				$conn = ftp_connect("g5.kekenet.com") or die("Could not connect");
				ftp_login($conn,'kekenetmp3','d$6d7bec292c7b11f%');
				ftp_mkdir_recusive($conn, dirname($o));
				ftp_put($conn,$fname,$real_file,FTP_ASCII);
				ftp_close($conn);
			}
		}
		
		if($_FILES['lrc_file']['error'] == 0) {
			$f = $_FILES['lrc_file'];
			
			$fdir = date('/Y/m/');
			$fname = $f['name'];
			if(!is_dir(ujn::get_cfg('thumb_path') . $fdir)) {
				mkdir(ujn::get_cfg('thumb_path') . $fdir, 0777, true);
			}
			$real_file = ujn::get_cfg('thumb_path') . $fdir . $fname;
			if(move_uploaded_file($f["tmp_name"], $real_file)) {
				$_o = "tmp/{$fdir}{$fname}";
				$conn = ftp_connect("www.kekenet.com") or die("Could not connect");
				ftp_login($conn,'uploadlrc','7c#829c4fa85f30$a9');
				ftp_mkdir_recusive($conn, dirname($_o));
				ftp_put($conn,$fname,$real_file,FTP_ASCII);
				ftp_close($conn);
			}
		}
		*/
		$o = '';
		if(isset($_SESSION['music_file']) && !empty($_SESSION['music_file'])) {
			$o = $_SESSION['music_file'];
			$_SESSION['music_file'] = '';
		}
		return $o;
	}
		
	private function bind_copyfrom($siteid, $url, $name, $copyfrom) {
		$out = '';
		if(empty($copyfrom)) {
			if(empty($url) || empty($name)) {
				$out = "本站原创|0";
			} else {
				$out = "<a href='{$url}' target='_blank'>{$name}</a>|0";
			}
		} else {
			$out = "|{$copyfrom}";
		}
		return tls_func::escape($out);
	}
	
	private function bind_url($siteid, $id) {
		
		$data = mdl_news::get_instance()->get($id);
		$datas = mdl_category::get_instance()->get_sub($siteid, array());
		
		$curr_cat = array();
		if(isset($datas[$data['info']['catid']])) {
			$curr_cat = $datas[$data['info']['catid']];
			$arrparentid = explode(',', $curr_cat['arrparentid']);
		
			$data['p_path'] = array();
			foreach($arrparentid as $v) {
				if(!empty($v))
					$data['p_path'][] = $datas[$v];
			}
			$data['p_path'][] = $curr_cat;
		}
		
		// $curr_cat = mdl_category::get_instance()->get($data['catid']);
		return $this->make_static_path($data, $curr_cat);
	}
	
	private function bind_tags($siteid, $tags) {
		
		$tags = array_filter(explode(',', $tags));
		if(!empty($tags)) {
			$tags_x = implode('\',\'', $tags);
			$sql = "select `tagid`, `tag` from `v9_tags` where tag in ('{$tags_x}') AND siteid='{$siteid}';";
			$tags_data = array();
			foreach($this->mysql()->find_all($sql) as $d) {
				$tags_data[$d['tag']] = $d;
			}
		
			$new_tag = $up_tag = array();
			foreach($tags as $t) {
				if(!isset($tags_data[$t])) {
					$new_tag[] = $t;
				} else {
					$up_tag[] = $tags_data[$t]['tagid'];
				}
			}
		
			if(!empty($new_tag)) {
				$add_values = array();
				foreach($new_tag as $tag) {
					$add_values[] = "('{$tag}','1',unix_timestamp(),unix_timestamp(),'{$siteid}')";
				}
				$add_values = implode(',', $add_values);
				$sql = "insert into `v9_tags`(`tag`,`usetimes`,`lastusetime`,`lasthittime`,`siteid`) values {$add_values} ;";
				$this->mysql()->insert($sql);
			}
		
			if(!empty($up_tag)) {
				$up_tag = implode('\',\'', $up_tag);
				$sql = "update `v9_tags` set `usetimes`=usetimes+1,`lastusetime`=unix_timestamp() where tagid in ('{$up_tag}') AND siteid='{$siteid}';";
				$this->mysql()->update($sql);
			}
		}
		
		return $tags;
	}
	
	function modify($params, $siteid, $id) {
		$tags = $this->bind_tags($siteid, $params['keywords']);
		
		$params['inputtime'] = strtotime($params['inputtime']);
		$params['url'] = $this->bind_url($siteid, $id);
		
		$params['copyfrom'] = $this->bind_copyfrom($siteid, $params['copyurl'], $params['copyname'], $params['copyfrom']);
		
		$params['thumb'] = $this->bind_thumb();
		
		$params['fileurl'] = $this->bind_music($params);
		
		$params['style'] = '0';
		$params['posids'] = isset($params['posids']) ? (int)$params['posids'] : 0;
		$params['status'] = 99;
		$params['sysadd'] = '0';
		$params['islink'] = isset($params['islink']) ? (int)$params['islink'] : 0;
		$params['username'] = $params['author'];
		$params['updatetime'] = NOW;
		$params['attribute'] = isset($params['attribute']) ? ',' . implode(',', $params['attribute']) : '';
		$params['keywords'] = implode(' ', $tags);
		$params['typeid'] = '0';
		$params['title'] = tls_func::escape($params['title']);
		$params['description'] = tls_func::escape($params['description']);
		$params['readpoint'] = 0;
		$params['groupids_view'] = '';
		$params['paginationtype'] = isset($params['paginationtype']) ? (int)$params['paginationtype'] : 0;
		$params['maxcharperpage'] = 0;
		$params['paytype'] = 0;
		$params['relation'] = '';
		$params['voteid'] = 0;
		$params['allow_comment'] = 1;
		$params['pdf_url'] = '';
		$params['template'] = isset($params['template']) ? $params['template'] : '';
		$params['isnot'] = isset($params['isnot']) ? $params['isnot'] : 0;
		//$params['content'] = tls_func::escape($params['content']);
		
		if(isset($params['islink']) && (int)$params['islink'] == 1) {
			$params['url'] = trim($params['linkurl']);
		}
		// index
		$sql =<<<EOT
update `v9_news` set 
`catid`='{$params['catid']}',`title`='{$params['title']}',`style`='{$params['style']}',`thumb`='{$params['thumb']}',`keywords`='{$params['keywords']}',
`description`='{$params['description']}',`posids`='{$params['posids']}',`url`='{$params['url']}',`islink`='{$params['islink']}',`inputtime`='{$params['inputtime']}',
`updatetime`=unix_timestamp(),`attribute`='{$params['attribute']}' 
where `id`='{$id}';
EOT;
		$this->mysql()->update($sql);
		
		// content
		$sql =<<<EOT
update `v9_news_data` set 
`content`='{$params['content']}',`readpoint`='{$params['readpoint']}',`groupids_view`='{$params['groupids_view']}',
`paginationtype`='{$params['paginationtype']}',`maxcharperpage`='{$params['maxcharperpage']}',`template`='{$params['template']}',
`paytype`='{$params['paytype']}',`relation`='{$params['relation']}',`voteid`='{$params['voteid']}',`allow_comment`='{$params['allow_comment']}',
`copyfrom`='{$params['copyfrom']}',`author`='{$params['author']}',`fileurl`='{$params['fileurl']}',`isnot`='{$params['isnot']}' 
where id='{$id}';
EOT;
		$this->mysql()->update($sql);
		
		$params['kkq_q'] = tls_func::escape($params['kkq_q']);
		$params['kkq_a'] = tls_func::escape($params['kkq_a']);
		// kkq
$sql =<<<EOT
insert into `v9_practise_qa` set
`news_id` = '{$id}', `question` = '{$params['kkq_q']}', `answer` = '{$params['kkq_a']}'
ON DUPLICATE KEY UPDATE `question` = '{$params['kkq_q']}', `answer` = '{$params['kkq_a']}';
EOT;
		$this->mysql()->update($sql);
		return $id;
	}
	
	function add($params, $siteid) {
		$tags = $this->bind_tags($siteid, $params['keywords']);
		$params['copyfrom'] = $this->bind_copyfrom($siteid, $params['copyurl'], $params['copyname'], $params['copyfrom']);
		
		$params['inputtime'] = strtotime($params['inputtime']);
		
		$params['thumb'] = $this->bind_thumb();
		
		$params['fileurl'] = $this->bind_music($params);
		
		$params['style'] = '0';
		$params['posids'] = isset($params['posids']) ? (int)$params['posids'] : 0;
		$params['status'] = 99;
		$params['sysadd'] = '0';
		$params['islink'] = isset($params['islink']) ? (int)$params['islink'] : 0;
		$params['username'] = $params['author'];
		$params['updatetime'] = NOW;
		$params['attribute'] = isset($params['attribute']) ? ',' . implode(',', $params['attribute']) : '';
		$params['keywords'] = implode(' ', $tags);
		$params['typeid'] = '0';
		$params['url'] = '';
		$params['title'] = tls_func::escape($params['title']);
		$params['description'] = tls_func::escape($params['description']);
		$params['readpoint'] = 0;
		$params['groupids_view'] = '';
		$params['paginationtype'] = isset($params['paginationtype']) ? (int)$params['paginationtype'] : 0;
		$params['maxcharperpage'] = 0;
		$params['paytype'] = 0;
		$params['relation'] = '';
		$params['voteid'] = 0;
		$params['allow_comment'] = 1;
		$params['pdf_url'] = '';
		$params['template'] = isset($params['template']) ? $params['template'] : '';
		$params['fileurl'] = isset($params['fileurl']) ? $params['fileurl'] : '';
		$params['isnot'] = isset($params['isnot']) ? $params['isnot'] : 0;
		//$params['content'] = tls_func::escape($params['content']);
		
		if(isset($params['islink']) && (int)$params['islink'] == 1) {
			$params['url'] = trim($params['linkurl']);
		}
		// index
		$sql =<<<EOT
insert into `v9_news`
(`catid`,							`pdf_url`, 							`url`,						 `title`,						 `typeid`,						 `style`,							`thumb`,						 `keywords`,						 `description`,							`posids`,							`status`,							`sysadd`,							`islink`,							`username`,							`inputtime`,						 `updatetime`,						 `attribute`) values
('{$params['catid']}','{$params['pdf_url']}', '{$params['url']}','{$params['title']}','{$params['typeid']}','{$params['style']}','{$params['thumb']}','{$params['keywords']}','{$params['description']}','{$params['posids']}','{$params['status']}','{$params['sysadd']}','{$params['islink']}','{$params['username']}','{$params['inputtime']}','{$params['updatetime']}','{$params['attribute']}');		
EOT;
		$new_id = $this->mysql()->insert($sql);
		if(empty($new_id)) {
			return 0;
		}
		
		// 静态地址
		$url = $this->bind_url($siteid, $new_id);
		$sql = "update `v9_news` set `url` = '$url' where `id` = '{$new_id}' limit 1;";
		$this->mysql()->update($sql);
		
		// content 
		$sql =<<<EOT
insert into `v9_news_data`
	set `id` = '{$new_id}', `content` = '{$params['content']}', `readpoint`  = '{$params['readpoint']}',
	`groupids_view`  = '{$params['groupids_view']}',
	`paginationtype` = '{$params['paginationtype']}',`maxcharperpage` = '{$params['maxcharperpage']}',
	`template` = '{$params['template']}',`paytype` = '{$params['paytype']}',
	`relation` = '{$params['relation']}',`voteid` = '{$params['voteid']}',`allow_comment` = '{$params['allow_comment']}',
	`copyfrom` = '{$params['copyfrom']}',
	`author` = '{$params['author']}',`fileurl` = '{$params['fileurl']}',`isnot` = '{$params['isnot']}'; 
EOT;
		if(false === $this->mysql()->insert($sql)) {
			$this->mysql()->delete("delete from `v9_news` where `id` = '{$new_id}' limit 1;");
			return 0;
		}
		
		$params['kkq_q'] = tls_func::escape($params['kkq_q']);
		$params['kkq_a'] = tls_func::escape($params['kkq_a']);
		// kkq
$sql =<<<EOT
insert into `v9_practise_qa` (`news_id`,`question`,`answer`) 
	values ('{$new_id}','{$params['kkq_q']}','{$params['kkq_a']}');
EOT;
		$this->mysql()->insert($sql);
		
		return $new_id;
	}
  
	function make_static_path($data, $curr_cat) {
		
		$setting = array();
		eval("\$setting = {$curr_cat['setting']};");
		$show_ruleid = isset($setting['show_ruleid']) ? $setting['show_ruleid'] : '1';
		
		$urlrule = ujn_model::get_instance('ujn_model')->mysql()->find_one("select * from `v9_urlrule` where `urlruleid`='{$show_ruleid}' limit 1;");
		$urlrules_arr = explode('|',$urlrule['urlrule']);
		$urlrule = $data['info']['page'] <= 1 ? $urlrules_arr[0] : $urlrules_arr[1];
		
		$categorydir = ( isset($data['p_path']) && isset($data['p_path'][0]) && isset($data['p_path'][0]['catdir']) ) ? $data['p_path'][0]['catdir'] : '';
		$catdir = $curr_cat['catdir'];
		if($categorydir == ''){
			$categorydir = $catdir.'/';
		}else{
			$categorydir = $categorydir.'/';
		}
		
		$d = explode('.', date('Y.m.d', $data['info']['inputtime']));
		
		$urls = str_replace(
				array('{$categorydir}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$id}','{$page}'),
				array($categorydir, $catdir, $d[0], $d[1], $d[2], $data['info']['catid'], $data['info']['id'],$data['info']['page']),
				$urlrule
		);
		return '/'.$urls;
	}
	
	function del($id) {
		$this->mysql()->delete("delete from `v9_news` where `id` = '{$id}' limit 1;");
		$this->mysql()->delete("delete from `v9_news_data` where `id` = '{$id}' limit 1;");
		$this->mysql()->delete("delete from `v9_practise_qa` where `news_id` = '{$id}' limit 1;");
	}
	
	function get($id) {
		return array(
				'info' => $this->mysql()->find_one("select * from `v9_news` where `id` = '{$id}' limit 1;"),
				'data' => $this->mysql()->find_one("select * from `v9_news_data` where `id` = '{$id}' limit 1;"),
				'kkq' => $this->mysql()->find_one("select * from `v9_practise_qa` where `news_id` = '{$id}' limit 1;")
		);
	}

	function get_hit($ids, $siteid = 1) { 
		// c-1-{$id}   
		foreach($ids as $k => $f) {
			$ids[$k] = "c-{$siteid}-{$f}";
		}
		if(empty($ids)) return array();
		$ids = implode('\',\'', $ids);

		$sql =<<<EOT
select * from v9_hits
		where `hitsid` in ('{$ids}');
EOT;
		return $this->mysql()->find_all($sql);   
	} 
	
	function hit($siteid, $id, $catid) {
		$sql =<<<EOT
insert into v9_hits set 
		`hitsid` = 'c-{$siteid}-{$id}', `catid` = '{$catid}', `views` = '0',
		`weekviews` = '0', `dayviews` = '0', `yesterdayviews` = '0',
		`monthviews` = '0', `updatetime` = unix_timestamp()
		on duplicate key update 
			`updatetime` = unix_timestamp(),
			`views` = `views` + 1, 
			`weekviews` = `weekviews` + 1, 
			`dayviews` = `dayviews` + 1, 
			`monthviews` = `monthviews` + 1;
EOT;
		$this->mysql()->insert($sql);
	}
	
	function get_file($id) {
		return array(
				'data' => $this->mysql()->find_one("select `author`,`fileurl` from `v9_news_data` where `id` = '{$id}' limit 1;")
		);
	}
	
	function get_files($ids, $siteid = 1) { 
		if(empty($ids)) return array();
		$ids = implode('\',\'', $ids);

		$sql =<<<EOT
select `id`,`author`,`fileurl` from `v9_news_data` where `id` in ('{$ids}');
EOT;
		return $this->mysql()->find_all($sql);   
	} 
	
	function get_tagss($ids, $siteid = 1) { 
		if(empty($ids)) return array();
		$ids = implode('\',\'', $ids);
		
		$sql =<<<EOT
select t.tagid,c.tag,c.contentid from `v9_tags_content` c left join `v9_tags` t on c.tag = t.tag
		where c.contentid in ('{$ids}') and t.siteid = '{$siteid}';
EOT;
		
		return $this->mysql()->find_all($sql);   
	} 
	
	function get_catids($catids, $offset = 0, $page_max = 20, $unpage = 0, $fields = '*') {
		if(empty($catids)) return array(
				'count' => 0,
				'data' => array()
				);
		$catids = implode('\',\'', $catids);
		if($unpage == 1) {
			$d = array('c' => 0);
		} else {
			$d = $this->mysql()->find_one("select count(1) c from `v9_news` where `catid` in ('{$catids}');");
		}
		$sql_data = "select {$fields} from `v9_news` where `catid` in ('{$catids}') order by id desc limit {$offset}, {$page_max};";
		return array(
				'count' => $d['c'],
				'data' => $this->mysql()->find_all($sql_data)
				);
	}

	/*
	 * 获取tags标签
	 */
	function get_tags($id,$siteid){
		
		$sql =<<<EOT
select t.tagid,c.tag from `v9_tags_content` c left join `v9_tags` t on c.tag = t.tag
		where c.contentid = '{$id}' and t.siteid = '{$siteid}';
EOT;
		return $this->mysql()->find_all($sql);
	}
	
	/*
	 * 获取感兴趣的文章
	 */
	function get_interest($id, $catid, $limit=4) {
		
		$sql =<<<EOT
select n.title,n.thumb,n.description,n.url,n.inputtime,n.attribute,d.author,d.fileurl from `v9_news` n left join `v9_news_data` d on n.id = d.id
		where n.status = 99 and n.catid = '{$catid}' and n.id!='{$id}' order by rand() limit {$limit};
EOT;
		return $this->mysql()->find_all($sql);
	}
	
  /**
  * @return mdl_news
  */
  static function get_instance($empty = '') {
    return parent::get_instance(__CLASS__);
  }
}